(function(app){
	app
		.controller("content_17_inputCtrl",["$scope","myFactory",'$http','$stateParams','$state',"$q",'$timeout','$location','$ionicHistory',function($scope,myFactory,$http,$stateParams,$state,$q,$timeout,$location,$ionicHistory){
			
			//参数定义、接收
			var itemId = $stateParams.changeTypeId;//变更项目ID
			var chdrnum01 =  $stateParams.chdrnum01; //保单号
			var chdrcoy = $stateParams.chdrcoy; //保单公司号码
			var policyData;//保单详情
			var itemData;//用于接收初始化查询initContentItem的内容，里面存在各种各样的内容，比如item02_1
			var searchParam = $stateParams.searchParam;
			var initFlag = false;//检测标志，在初始化函数完成后，会被置为true
			var _productType ="";//产品类型，定义为全局变量方便使用
			//绑定参数到页面
			$scope.chdrnum01 = chdrnum01;
			$scope.readFlag = false;//阅读协议标志，默认为false
			$scope.invAmntFlag = false; //万能区域，默认隐藏
			$scope.uniAmntFlag = false; //投连区域：金额，默认隐藏
			$scope.acctFlag = false;    //投连区域：产品选择区域，默认隐藏
			var token=sessionStorage.getItem("token");
			//页面同意阅读协议复选框部分
			$scope.changeReadFlag = function(){
				$scope.readFlag = !$scope.readFlag;
				console.log($scope.readFlag);
			}
			
			//重新受理
			$scope.renew = function(){
				myFactory.renew();
			}	
			//退出移动保全
			$scope.exit = function(){
				myFactory.exit();
			}
			//返回上一页
			$scope.goBack = function(){
				myFactory.goBack();
			}
/**********************************************初始化函数begin****************************************************/
			//初始化查询变更项内容
			$scope.load = function () {
				myFactory.loadingShow();//显示加载圈
				var timestamp=myFactory.getTimetamp();
				var sfis= "itemId-token-timestamp";
				var signStr="itemId="+itemId+"&token="+token+"&timestamp="+timestamp;//encodeURI(name)
				var sign = myFactory.hex(signStr);
				//初始化查询变更项内容
				$http({
					method: 'GET',
					url: app.domain + 'input/initContentItem.action',
					params: {'itemId': itemId,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
				}).then(function successCallback(response) {
					if (response.data.success) {
						itemData = response.data.data.modelMap;
						$scope.item17 = itemData.item17;
						$scope.accounts = itemData.accounts;
						//中信保诚「智尚人生」年金保险E款（投资连结型）add by csf 20190815 start
						var tempAccounts = [];//缓存筛选后的账户
						//中信保诚「智尚人生」年金保险E款（投资连结型）add by csf 20190815 end
						if($scope.accounts!=undefined && $scope.accounts!=null && $scope.accounts!=""){
							for(var i=0;i<$scope.accounts.length;i++){
								$scope.accounts[i].funddesc=$scope.accounts[i].funddesc.replace("投资账户","");
								//中信保诚「智尚人生」年金保险E款（投资连结型）add by csf 20190815 start
								if (itemData.crtable == 'USBC') {
									if ($scope.accounts[i].vfund.trim() == 'IIGD'||$scope.accounts[i].vfund.trim() == 'MIGD') {
										tempAccounts.push($scope.accounts[i]);
									}
								} else {
									if ($scope.accounts[i].vfund.trim() != 'IIGD') {
										tempAccounts.push($scope.accounts[i]);
									}
								}
								//中信保诚「智尚人生」年金保险E款（投资连结型）add by csf 20190815 end
							}
						}
						//中信保诚「智尚人生」年金保险E款（投资连结型）add by csf 20190815 start
						if (tempAccounts.length != 0 ) {
							$scope.accounts = tempAccounts;
						}
						//中信保诚「智尚人生」年金保险E款（投资连结型）add by csf 20190815 end
//						console.log($scope.item17);
						
						 _productType = $scope.item17.productType;	//	产品类型，作为全局变量在开头已经定义
						//var _InvAmnt 	= $("#InvAmnt");	 //	万能区域
						//var _UniAmnt 	= $("#UniAmnt");	 //	投连区域：金额
						//var _InvAmntAcct= $("#InvAmntAcct");//	投连区域：产品选择区域
						//	存在投连产品时显示
						if( _productType.indexOf("U") > -1 ){
							//	取消隐藏
							//_UniAmnt.style.display 		='';
							//_InvAmntAcct.style.display  ='';
							$scope.invAmntFlag = false; //万能区域，隐藏
							$scope.uniAmntFlag = true; //投连区域：金额，显示
							$scope.acctFlag = true;    //投连区域：产品选择区域，显示

						}
						//	存在万能产品时显示		
						if( _productType.indexOf("W") > -1 ){
							//_InvAmnt.style.display ='';
							$scope.invAmntFlag = true; //万能区域，显示
						}
						
						//这部分校验提取到要下一步时候才执行
//						var _AccountUniAmnt = $("#accountUniAmnt");
//						var _AccountInvAmnt = $("#accountInvAmnt");
//						_AccountInvAmnt.required="";
//						_AccountUniAmnt.required = "";
//						//	为投连产品时必须输入投连金额
//						if( _productType == "U" ){
//							_AccountUniAmnt.required = "required" ;
//						}
//						
//						//	为万能产品时必须输入万能金额
//						if( _productType == "W" ){
//							_AccountInvAmnt.required = "required" ;
//						}

						initFlag=true;//标识初始化成功
					}
					myFactory.loadingHide();
				}, function errorCallback(response) {
					myFactory.loadingHide();
					myFactory.alert("","初始化查询变更项内容失败!","info");
				});
			}
/**********************************************初始化函数end****************************************************/				
			//保单详情弹框
			$scope.showPolicyDetail = function(){
				modal('open','policyModalOn17Input','overwindowOn17Input','policyCloseXOn17Input');
				var timestamp=myFactory.getTimetamp();
				var sfis= "chdrnum-chdrcoy-token-timestamp";
				var signStr="chdrnum="+chdrnum01+"&chdrcoy="+chdrcoy+"&token="+token+"&timestamp="+timestamp;//encodeURI(name)
				var sign = myFactory.hex(signStr);
				//初始化时候查询保单详情
				$http({
					method: 'GET',
					url: app.domain + 'query/restFindPolicyDetail.action',
					params: {'chdrnum': chdrnum01,'chdrcoy': chdrcoy,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
				}).then(function successCallback(response) {
					if (response.data.success) {
						policyData = response.data.data;
						$scope.policyData = policyData;
						$scope.policyData.ptdate01=myFactory.DateTools($scope.policyData.ptdate01);
					}
				}, function errorCallback(response) {
					myFactory.alert("","初始化查询订单详情失败!","info");
				});
			}
			//保单详情弹窗关闭函数
			$scope.policyCancelOn17Input = function(){
				modal('close','policyModalOn17Input','overwindowOn17Input','policyCloseXOn17Input');
			}
			//关闭遮罩
			$scope.overwindowClose = function(){
				//$(".overwindow").show();
				$(".overwindow").hide();
				$(".overmodal").hide();
			}

			//客户须知
			$scope.tipOpen = function(){
				modal('open','tip_model','overwindowOn17Input');
			}
			$scope.closeTip = function(){
				modal('close','tip_model','overwindowOn17Input');
			}
			
			/**
			 * 只输入整数函授
			 */
			$scope.keyNumPress = function(){
				var keyCode = event.keyCode;
				if(keyCode>=48 && keyCode<=57){
					event.returnValue = true;
				}else{
					event.returnValue = false;
				}
			}
			
			//合计
			$scope.keyNumUp = function(){
				var sum = 0
				for(var i=0;i<$scope.accounts.length;i++){
					var val = $("#accountRateFor17Input_"+i).val();
					if($("#accountRateFor17Input_"+i).val() == null || $("#accountRateFor17Input_"+i).val() == ''){
						val = 0;
					}
					sum += parseInt(val);
				}
				$("#extra_investment_sum").val(sum);
			}
			
			//下一步
			$scope.nextStep = function(){
				myFactory.loadingShow();//显示加载圈
				//判断是否初始化完成了，如果失败，不予进入下一步
				if(!initFlag){
					myFactory.alert("","初始化时失败，请返回上一步重试","info");
					myFactory.loadingHide();
					return;
				}
				if($scope.readFlag == false){
					myFactory.alert("","请先同意《申请须知》!","info");
					myFactory.loadingHide();
					return;
				}
				
				//两个字段不能同时是空的
				if( $("#accountInvAmnt").val() == "" && $("#accountUniAmnt").val() == "" ){
					myFactory.alert("","投连或万能金额不能为空，需重新确认!","info");
					myFactory.loadingHide();
					return false;
		    	}
				//为投连产品时必须输入投连金额
				if( _productType == "U" ){
					if($("#accountUniAmnt").val() == ""){
						myFactory.alert("","投连金额不能为空，需重新确认!","info");
						myFactory.loadingHide();
						return false;
					}
				}
				//为万能产品时必须输入万能金额
				if( _productType == "W" ){
					if($("#accountInvAmnt").val() == ""){
						myFactory.alert("","万能金额不能为空，需重新确认!","info");
						myFactory.loadingHide();
						return false;
					}
				}

		    	//	填写了投连产品金额时 ，需要对比例进行观测
		        if( $("#accountUniAmnt").val() !="" ){
		    	
		        	var _accountRate = $("input[name='accountRateFor17Input']");
		        	var rateSum = 0 ; //	比例总值
		        	
		        	/*S2022032221697_中信保诚智尚人生年金保险C款新增“盛世嘉享、盛世优享”投资账户 add by huanghaokun 20220510 start*/
		        	//当次买入/转入投资账户不可超10个
		        	var accountRateCount = 0;
		        	/*S2022032221697_中信保诚智尚人生年金保险C款新增“盛世嘉享、盛世优享”投资账户 add by huanghaokun 20220510 end*/
		        	//	遍历所有投资账户信息，把不为空值的的投资比例信息进行总计
					for(var i = 0 ; i < _accountRate.length ; i ++ ){
						var rate = _accountRate[i].value ;	//	当前比例值
					 	if( "" != rate.trim() ){
					 		rateSum = rateSum + parseInt(rate);
					 		/*S2022032221697_中信保诚智尚人生年金保险C款新增“盛世嘉享、盛世优享”投资账户 add by huanghaokun 20220510 start*/
					 		accountRateCount++;
					 		/*S2022032221697_中信保诚智尚人生年金保险C款新增“盛世嘉享、盛世优享”投资账户 add by huanghaokun 20220510 end*/
					 	}
					}
					
					/*S2022032221697_中信保诚智尚人生年金保险C款新增“盛世嘉享、盛世优享”投资账户 add by huanghaokun 20220510 start*/
					if(accountRateCount>10){
						myFactory.alert("","当次买入/转入投资账户不可超10个","info");
						myFactory.loadingHide();
						return false;
					}
					/*S2022032221697_中信保诚智尚人生年金保险C款新增“盛世嘉享、盛世优享”投资账户 add by huanghaokun 20220510 end*/
					
					if( rateSum == 0 ){
						myFactory.alert("","额外投资账户分配比例为0，需重新确认!","info");
						myFactory.loadingHide();
						return false;
					}
					if( rateSum!=100 ){
						myFactory.alert("","额外投资账户分配比例和不等于100%，需重新确认!","info");
						myFactory.loadingHide();
						return false;
					}			
		        }
                //校验完成，开始封装数据
                var a = $("input[name='accountTypeFor17Input']");//投资账户类型
                var b = $("input[name='accountRateFor17Input']");//投资账户比例
                /*《S2018082805259-投资风险测评保全系统需求》jiyongchang 20190610 start*/
                var C = $("input[name='accountValueFor17Input']");//投资账户比例
                /*《S2018082805259-投资风险测评保全系统需求》jiyongchang 20190610 end*/
                
                var accountTypes = "";
                var accountRates = "";
                /*《S2018082805259-投资风险测评保全系统需求》jiyongchang 20190610 star*/
                var accountValues = "";
                /*《S2018082805259-投资风险测评保全系统需求》jiyongchang 20190610 end*/
                for(var i=0;i<a.length;i++){
                    if(i!=0){
                        accountTypes = accountTypes + ",";
                    }
                    accountTypes = accountTypes + $("#accountTypeFor17Input_"+i).val().trim();
                }

                for(var i=0;i<b.length;i++){
                    if(i!=0){
                        accountRates = accountRates + ",";
                    }
                    accountRates = accountRates + $("#accountRateFor17Input_"+i).val().trim();
                }
                /*《S2018082805259-投资风险测评保全系统需求》jiyongchang 20190610 star*/
                for(var i=0;i<b.length;i++){
                	if(i!=0){
                		accountValues = accountValues + ",";
                	}
                	accountValues = accountValues + $("#accountValueFor17Input_"+i).val().trim();
                }
                /*《S2018082805259-投资风险测评保全系统需求》jiyongchang 20190610 end*/
                
                var item={
                    "itemId":itemId,
                    "accountInvAmnt":$("#accountInvAmnt").val(),//万能投资金额
                    "accountUniAmnt":$("#accountUniAmnt").val(),//投连投资金额
                    "accountTypes":accountTypes,//投资账户类型
                    "accountRates":accountRates,//投资账户比例
                    /*《S2018082805259-投资风险测评保全系统需求》jiyongchang 20190610 star*/
                    "accountValues":accountValues,//投资账户名称
                    /*《S2018082805259-投资风险测评保全系统需求》jiyongchang 20190610 end*/
                }

                myFactory.loadingHide();
                
    			/*
    			 * ********************************************************************
    			 * 	《S2018082805259-投资风险测评保全系统需求》（add by jiangwy 20190531 ) star
    			 * 
    			 * 1、检查风险评测参数信息
    			 * 2、是否进入评测页面判断
    			 * 
    			 *********************************************************************/ 
                /*$ionicHistory.clearCache().then(function(){
                    $state.go('content_check_main',{
                        itemId:itemId,
                        item:item,
                        chdrnum01:chdrnum01,
                        chdrcoy:chdrcoy
                    });
                })*/
                var timestamp=myFactory.getTimetamp();
				var sfis= "token-timestamp";
				var signStr="token=" + token + "&timestamp=" + timestamp;//encodeURI(name)
				var sign = myFactory.hex(signStr);
				var reqData = {
						"chdrcoy":chdrcoy,
						"chdrnum":chdrnum01,
						"itemId": itemId,
						"itemStr":item
				}
    			$http({
    				method: 'POST',
    				url: app.domain + 'riskevaluate/checkRisk.action',
    				data:{paramsMap:reqData,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
    			}).then(function successCallback(response) {
    				if (response.data.success) {
    					var resultData = response.data.data.modelMap;  
    					//	【本次买入账户风险等级】
    					$scope.inputRiskGrade = resultData.inputRiskGrade;
    					//	是否需要风险评测
    					$scope.isEvaluate     = resultData.isEvaluate;
    					//	路由 nextUrl 地址，默认为：审核页面
    					var nextUrl = "content_check_main";
    					//	如果风险评测结果值为“N”，则直接跳过该风险评测页面进入审核页面
    					if( "Y" == $scope.isEvaluate ){
    						//	进入风险评测页面
    						nextUrl = "invest_risk_evaluate";
    					}
    					
    					//	路由跳转
//		                $ionicHistory.clearCache().then(function(){
		                    $state.go( nextUrl ,{
		                        itemId:itemId,
		                        item:item,
		                        chdrnum01:chdrnum01,
		                        chdrcoy:chdrcoy,
		                        inputRiskGrade:$scope.inputRiskGrade
		                    });
//		                })
    				}
    				myFactory.loadingHide();
    			}, function errorCallback(response) {
    				myFactory.loadingHide();
    				myFactory.alert("","初始化查询风险评测失败!","info");
    			});
    			
   			 	/* 
    			 * ********************************************************************
    			 * 	《S2018082805259-投资风险测评保全系统需求》（add by jiangwy 20190531 ) end
    			 * 
    			 * ********************************************************************/ 
    			
                
			}
		   

    		/**
			 * S2018062604412网联政策630实施相关系统功能改造需求（移动保全2.0增加签约功能）
			 * 新增签约接口的逻辑 add by csf 20180926 end
			 */
		}]);  
		//指针弹窗
		app.directive('infoid',function(){
			return {
				restrict: 'EA',		//指明指令在DOM里面以什么形式被声明,EA.表示即可以是元素也可以是属性
				templateUrl: 'html/input/content_base_info.html'+app.clearCache,
				replace: true,		//设置解析后，DOM声明的指令是否消失
				link: function(scope,element,attrs){  //链接函数负责注册DOM事件和更新DOM,
					console.log('指令完成');
				}
			}
		});
})(app)